package com.lb.shopguide.ui.fragment.boss;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.MerchantBean;
import com.lb.shopguide.entity.local.AreaBean;
import com.lb.shopguide.event.boss.ChangeMerchantNameEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.dialog.DialogCommonEdittext;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2018/1/19.
 */

public class FragmentEditMerchantInfo extends BaseCommonFragment {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.rl_merchant_name)
    RelativeLayout rlMerchantName;
    @BindView(R.id.rl_charge_man)
    RelativeLayout rlChargeMan;
    @BindView(R.id.rl_mobile_phone)
    RelativeLayout rlMobileNumber;
    @BindView(R.id.rl_addr)
    RelativeLayout rlAddr;
    @BindView(R.id.rl_detail_addr)
    RelativeLayout rlDetailAddr;
    @BindView(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @BindView(R.id.tv_charge_man)
    TextView tvChargeMan;
    @BindView(R.id.tv_mobile_phone)
    TextView tvMobileNumber;
    @BindView(R.id.tv_store_num)
    TextView tvStoreNum;
    @BindView(R.id.tv_receive_account)
    TextView tvReceiveAccount;
    @BindView(R.id.tv_receive_true_name)
    TextView tvReceiveTrueName;
    @BindView(R.id.tv_user_name)
    TextView tvReceiveUsername;
    @BindView(R.id.tv_addr)
    TextView tvAddr;
    @BindView(R.id.tv_detail_addr)
    TextView tvDetailAddr;
    //    private RelativeLayout rlStoreNum;
//    private RelativeLayout rlReceiveAccount;
//    private RelativeLayout rlReceiveTrueName;
//    private RelativeLayout rlReceiveUsername;

    private MerchantBean mMerchantBean;

    private boolean infoChange = false;//商户信息修改
    private boolean isLoaded = false;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    public static FragmentEditMerchantInfo newInstance(MerchantBean merchantBean) {
        FragmentEditMerchantInfo fragmentEditMerchantInfo = new FragmentEditMerchantInfo();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.MERCHANT_BEAN, merchantBean);
        fragmentEditMerchantInfo.setArguments(bundle);
        return fragmentEditMerchantInfo;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_edit_merchant_info;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.MERCHANT_BEAN)) {
            mMerchantBean = (MerchantBean) bundle.getSerializable(AppConstant.MERCHANT_BEAN);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    public void initView() {
        ctb.setTvTitle("编辑商户资料");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop();
            }
        });
        bindData();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    private void bindData() {
        if (mMerchantBean != null) {
            tvStoreNum.setText("" + mMerchantBean.getActualStoreSum());
            tvReceiveUsername.setText(mMerchantBean.getUserName());
            tvReceiveTrueName.setText(mMerchantBean.getReceiveTrueName());
            tvReceiveAccount.setText(mMerchantBean.getReceiveAccount());
            tvMerchantName.setText(mMerchantBean.getMerchantName());
            tvDetailAddr.setText(mMerchantBean.getConnectAddress());
            tvChargeMan.setText(mMerchantBean.getChargeMan());
            tvMobileNumber.setText(mMerchantBean.getMobileNum());

            if (TextUtils.isEmpty(mMerchantBean.getDistrict())) {
                tvAddr.setText(mMerchantBean.getProvince() + "," + mMerchantBean.getCity());
            } else {
                tvAddr.setText(mMerchantBean.getProvince() + "," + mMerchantBean.getCity() + "," + mMerchantBean.getDistrict());
            }
        }
    }


    private void refresh() {
        sendRequestGetMerchantInfo();
    }

    @Override
    public String getPageTag() {
        return FragmentEditMerchantInfo.class.getName();
    }


    private void sendRequestGetMerchantInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mMerchantBean = (MerchantBean) JsonUtil.getObject(response.getReturnContent(), MerchantBean.class);
                    if (infoChange) {
                        infoChange = false;
                        EventBus.getDefault().post(new ChangeMerchantNameEvent(mMerchantBean));
                    }
                    bindData();
                }
            }
        };
        ApiMethodBoss.getMerchantInfo(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    @OnClick(R.id.rl_addr)
    void addrClick() {
        KeyboardUtils.hideSoftInput(_mActivity);
        if (isLoaded) {
            showPickerView();
        } else {
            Toast.makeText(mContext, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.rl_charge_man)
    void chargeManClick() {
        View editView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_enter, null);
        final EditText etContent = editView.findViewById(R.id.et_content);
        etContent.setText(mMerchantBean.getChargeMan());
        etContent.setSelection(mMerchantBean.getChargeMan().length());
        DialogCommonEdittext dialogChargeMan = new DialogCommonEdittext(mContext);
        dialogChargeMan.getAlertDialog(editView, "请输入负责人姓名").show();
        dialogChargeMan.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
            @Override
            public void onSure(DialogInterface dialog, int which) {
                String chargeMan = etContent.getText().toString();
                if (!TextUtils.isEmpty(chargeMan)) {
                    saveChange("chargeMan", chargeMan);
                } else {
                    ToastUtils.showShort("请输入正确的负责人姓名");
                }
                dialog.dismiss();
            }

            @Override
            public void onCancel(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    @OnClick(R.id.rl_merchant_name)
    void merchantNameClick() {
        View editView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_enter, null);
        final EditText etContent = editView.findViewById(R.id.et_content);
        etContent.setText(mMerchantBean.getMerchantName());
        etContent.setSelection(mMerchantBean.getMerchantName().length());
        DialogCommonEdittext dialogMerchant = new DialogCommonEdittext(mContext);
        dialogMerchant.getAlertDialog(editView, "请输入商户名称").show();
        dialogMerchant.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
            @Override
            public void onSure(DialogInterface dialog, int which) {
                String merchantName = etContent.getText().toString();
                if (!TextUtils.isEmpty(merchantName)) {
                    saveChange("merchantName", merchantName);
                } else {
                    ToastUtils.showShort("请输入正确的商户名称");
                }
                dialog.dismiss();
            }

            @Override
            public void onCancel(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    @OnClick(R.id.rl_mobile_phone)
    void mobilePhoneClick() {
        View editView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_enter, null);
        final EditText etContent = editView.findViewById(R.id.et_content);
        etContent.setText(mMerchantBean.getMobileNum());
        etContent.setSelection(mMerchantBean.getMobileNum().length());
        InputFilter[] filters = {new InputFilter.LengthFilter(11)};
        etContent.setFilters(filters);
        DialogCommonEdittext dialogMobile = new DialogCommonEdittext(mContext);
        dialogMobile.getAlertDialog(editView, "请输入联系电话").show();
        dialogMobile.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
            @Override
            public void onSure(DialogInterface dialog, int which) {
                String mobileNum = etContent.getText().toString();
                if (!TextUtils.isEmpty(mobileNum)) {
                    saveChange("mobileNum", mobileNum);
                } else {
                    ToastUtils.showShort("请输入正确的联系电话");
                }
                dialog.dismiss();
            }

            @Override
            public void onCancel(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    @OnClick(R.id.rl_detail_addr)
    void detailAddrClick() {
        View editView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_enter, null);
        final EditText etContent = editView.findViewById(R.id.et_content);
        etContent.setText(mMerchantBean.getConnectAddress());
        etContent.setSelection(mMerchantBean.getConnectAddress().length());
        DialogCommonEdittext dialogDetailAddr = new DialogCommonEdittext(mContext);
        dialogDetailAddr.getAlertDialog(editView, "请输入详细地址").show();
        dialogDetailAddr.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
            @Override
            public void onSure(DialogInterface dialog, int which) {
                String detailAddr = etContent.getText().toString();
                if (!TextUtils.isEmpty(detailAddr)) {
                    saveChange("connectAddress", detailAddr);
                } else {
                    ToastUtils.showShort("请输入正确的详细地址");
                }
                dialog.dismiss();
            }

            @Override
            public void onCancel(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    private HashMap getBaseData() {
        HashMap hashMap = new HashMap();
        hashMap.put("merchantName", mMerchantBean.getMerchantName());
        hashMap.put("chargeMan", mMerchantBean.getChargeMan());
        hashMap.put("mobileNum", mMerchantBean.getMobileNum());
        hashMap.put("province", mMerchantBean.getProvince());
        hashMap.put("city", mMerchantBean.getCity());
        hashMap.put("district", mMerchantBean.getDistrict());
        hashMap.put("connectAddress", mMerchantBean.getConnectAddress());
        return hashMap;
    }

    private void saveChange(String key, String value) {
        infoChange = true;
        HashMap hashMap = getBaseData();
        hashMap.put(key, value);
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        sendRequestSaveChange(body);
    }

    private void saveDistrict(String province, String city, String dis) {
        infoChange = true;
        HashMap hashMap = getBaseData();
        if (!TextUtils.isEmpty(province)) {
            hashMap.put("province", province);
        }
        if (!TextUtils.isEmpty(city)) {
            hashMap.put("city", city);
        }
        if (!TextUtils.isEmpty(dis)) {
            hashMap.put("district", dis);
        }
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        sendRequestSaveChange(body);
    }


    private void sendRequestSaveChange(RequestBody body) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ToastUtils.showShort("编辑商户信息成功");
                    refresh();
                }
            }

        };
        ApiMethodBoss.editMerchantInfo(new SimpleLbObserver(listener, otherListener), body, this, FragmentEvent.DESTROY_VIEW);
    }

    private void showPickerView() {// 弹出选择器
        LogUtils.d("options1Items size ===========" + options1Items.size());
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String province = options1Items.get(options1);
                String city = options2Items.get(options1).get(options2);
                String dis = options3Items.get(options1).get(options2).get(options3);
                String district = province + "," + city + "," + dis;
                tvAddr.setText(district);
                saveDistrict(province, city, dis);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(mContext, "开始解析数据", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(mContext, "解析数据成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(mContext, "解析数据失败", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private void initJsonData() {//解析数据

        ArrayList<AreaBean> jsonBean = parseData(mUserConfigManager.getDistrictInfo());//用Gson 转成实体

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            options1Items.add(jsonBean.get(i).getName());
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getChild().size(); c++) {//遍历该省份的所有城市
                AreaBean CityName = jsonBean.get(i).getChild().get(c);
                cityList.add(CityName.getName());//添加城市

                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChild().get(c).getChild() == null
                        || jsonBean.get(i).getChild().get(c).getChild().size() == 0) {
                    city_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getChild().get(c).getChild().size(); d++) {//该城市对应地区所有数据
                        AreaBean areaDis = jsonBean.get(i).getChild().get(c).getChild().get(d);

                        city_AreaList.add(areaDis.getName());//添加该城市所有地区数据
                    }
                }
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<AreaBean> parseData(String result) {//Gson 解析
        ArrayList<AreaBean> listPro = new ArrayList<>();
        try {
            JSONArray jsonProvinces = new JSONArray(result);
            for (int i = 0; i < jsonProvinces.length(); i++) {
                AreaBean areaPro = new AreaBean();
                JSONObject jsonPro = (JSONObject) jsonProvinces.get(i);
                String province = jsonPro.getString("v");
                areaPro.setName(province);
                if (jsonPro.has("c")) {
                    ArrayList<AreaBean> listCity = new ArrayList<>();
                    JSONArray jsonCitys = jsonPro.getJSONArray("c");
                    for (int j = 0; j < jsonCitys.length(); j++) {
                        AreaBean areaCity = new AreaBean();
                        JSONObject jsonCity = (JSONObject) jsonCitys.get(j);
                        areaCity.setName(jsonCity.getString("v"));
                        if (jsonCity.has("c")) {
                            ArrayList<AreaBean> listDis = new ArrayList<>();
                            JSONArray jsonDiss = jsonCity.getJSONArray("c");
                            for (int k = 0; k < jsonDiss.length(); k++) {
                                JSONObject jsonDis = (JSONObject) jsonDiss.get(k);
                                AreaBean areaDis = new AreaBean();
                                areaDis.setName(jsonDis.getString("v"));
                                listDis.add(areaDis);
                            }
                            areaCity.setChild(listDis);
                        }
                        listCity.add(areaCity);
                    }
                    areaPro.setChild(listCity);
                }
                listPro.add(areaPro);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return listPro;
    }
}
